package cn.codeforfun.exchage;

import cn.codeforfun.follower.Follower;
import cn.codeforfun.follower.FollowerDao;
import cn.codeforfun.prize.Prize;
import cn.codeforfun.prize.PrizeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by Administrator on 2017/2/18 0018.
 */
@Repository
public class ExchangeDaoImpl implements ExchangeCustom {
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private PrizeDao prizeDao;
    @Autowired
    private FollowerDao followerDao;
    private String followerAndPrizeSql = "" +
            "SELECT " +
            " e.follower_id, " +
            " e.`code`, " +
            " e.has_exchange, " +
            " e.has_prize, " +
            " e.prize_id, " +
            " e.vote_id, " +
            " e.has_get " +
            "FROM " +
            " follower_vote AS e " +
            "WHERE e.has_prize=1";

    @Override
    public List<Exchange> findWithFollowerAndPrize() {
        Query nativeQuery = entityManager.createNativeQuery(followerAndPrizeSql, Exchange.class);
        List<Exchange> resultList = nativeQuery.getResultList();
        for (Exchange exchange : resultList) {
            Follower follower = followerDao.findOne(exchange.getFollowerId());
            Prize prize = prizeDao.findOne(exchange.getPrizeId());
            exchange.setFollower(follower);
            exchange.setPrize(prize);
        }
        return resultList;
    }
}
